package com.example.ymm.modules1.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.model.em.EmSysNotePlatform;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.mapper.my.user.DbIntegralLogMapper;
import com.example.ymm.modules1.query.DbUserAdvanceDateQueryCriteria;
import com.example.ymm.modules1.service.dd.DingMiniNoticeService;
import com.example.ymm.modules1.service.dd.ms.DingNoticeService;
import com.example.ymm.modules1.service.dto.*;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.DateUtils;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.YearMonth;
import java.util.*;

@Service
@Slf4j
public class DbIntegralLogServiceImpl extends BaseServiceImpl<DbIntegralLogMapper, DbIntegralLog>
        implements DbIntegralLogService {

    @Autowired
    DbUserNoteService dbUserNoteService;
    @Autowired
    DbCardService dbCardService;
    @Autowired
    DbUserService dbUserService;
    @Autowired
    DbUserAdvanceDateService dbUserAdvanceDateService;
    @Autowired
    DingMiniNoticeService dingMiniNoticeService;

    @Value("${spring.profiles.active}")
    String PD_MATCH;

    @Autowired
    DbUserSignService dbUserSignService;

    @Override
    public TableList<DbIntegralLog> list(DbIntegralLogQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbIntegralLog> page = new Page<DbIntegralLog>(pageDto.getPage(), pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbIntegralLog.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DbIntegralLog> tableList = new TableList(page);
        return tableList;
    }

    public List<DbIntegralLog> queryAll(DbIntegralLogQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbIntegralLog.class, criteria);
        predicate.orderByDesc("create_time");
        List<DbIntegralLog> result = baseMapper.selectList(predicate);
        return result;
    }

    /**
     * 打卡查询今日读书累计积分
     * 添加读书积分记录
     *
     * @param dto
     * @param integral
     * @return
     */
    @Override
    public AddNoteResultDto queryReadTypeByToday(DbUserNoteDto dto, Integer integral) {

        Date now = new Date();
        String day = DateKit.dateFormat(now, "yyyy-MM-dd");

        Integer readType = 2;
        DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
        criteria.setType(1);
        criteria.setReadType(readType);
        String userId = getUserId();
        String userName = getUserName();
        criteria.setUserId(userId);
        criteria.setSysNote(EmSysNotePlatform.da_day.getType());
        criteria.setDay(day);
        // criteria.setIntegral(integral);
        List<String> list = DateUtils.getDateListByThisDay();

        criteria.setCreateTime(list);
        List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);

        AddNoteResultDto resultDto = new AddNoteResultDto();
        resultDto.setType(0);

        DbIntegralLog integralLog = null;
        if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
            integralLog = dbIntegralLogs.get(0);
            if (!integralLog.getIntegral().equals(integral)) {
                resultDto.setType(1);
                if (integral > integralLog.getIntegral()) {
                    // 这个积分是要累加的
                    resultDto.setIntegral(integral - integralLog.getIntegral());

                } else {
                    resultDto.setIntegral(integralLog.getIntegral() - integral);
                }
                integralLog.setIntegral(integral);
                saveOrUpdate(integralLog);
            }
        } else {
            integralLog = new DbIntegralLog();
            integralLog.setIntegral(integral);
            integralLog.setReadType(readType);
            integralLog.setUserId(userId);
            integralLog.setUserName(userName);
            integralLog.setNote("读书获得积分");
            integralLog.setDay(day);
            integralLog.setSysNote(EmSysNotePlatform.da_day.getType());
            integralLog.setType(1);
            resultDto.setType(1);
            resultDto.setIntegral(integral);
            saveOrUpdate(integralLog);

        }
        return resultDto;
    }

    ;

    @Override
    public AddNoteResultDto patchReadTypeByToday(DbUserNoteDto dto, Integer integral, String date) {
        Integer readType = 2;
        DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
        criteria.setType(1);
        criteria.setReadType(readType);
        criteria.setUserId(dto.getUserId());
        criteria.setSysNote(EmSysNotePlatform.bu_card.getType());
        criteria.setDay(date);
        // List<String> list=DateUtils.getDateListByThisDayByDate(date);
        //
        // criteria.setCreateTime(list);
        List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);

        AddNoteResultDto resultDto = new AddNoteResultDto();
        resultDto.setType(0);
        DbIntegralLog integralLog = null;
        if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
        } else {
            integralLog = new DbIntegralLog();
            integralLog.setIntegral(integral);
            integralLog.setReadType(readType);
            integralLog.setUserId(dto.getUserId());
            integralLog.setUserName(dto.getUserName());
            integralLog.setNote("读书获得积分");
            integralLog.setDay(date);
            integralLog.setType(1);
            integralLog.setSysNote(EmSysNotePlatform.bu_card.getType());

            // Date now = new Date();
            // now = DateKit.dateFormat(DateKit.dateFormat(now,date+" HH:mm:ss"));
            // integralLog.setCreateTime(new Timestamp(now.getTime()));
            resultDto.setType(1);
            resultDto.setIntegral(integral);
        }
        saveOrUpdate(integralLog);
        return resultDto;
    }

    @Override
    public AddNoteResultDto advanceReadTypeByToday(DbUserNoteDto dto, Integer integral, String date) {
        String userId = getUserId();
        String userName = getUserName();
        Integer readType = 2;
        DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
        criteria.setType(1);
        criteria.setReadType(readType);
        criteria.setUserId(userId);
        criteria.setSysNote(EmSysNotePlatform.tq_card.getType());
        criteria.setDay(date);
        // List<String> list=DateUtils.getDateListByThisDayByDate(date);
        //
        // criteria.setCreateTime(list);
        List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);

        AddNoteResultDto resultDto = new AddNoteResultDto();
        resultDto.setType(0);
        DbIntegralLog integralLog = null;
        if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
            integralLog = dbIntegralLogs.get(0);
            if (!integralLog.getIntegral().equals(integral)) {
                resultDto.setType(1);
                if (integral > integralLog.getIntegral()) {
                    // 这个积分是要累加的
                    resultDto.setIntegral(integral - integralLog.getIntegral());

                } else {
                    resultDto.setIntegral(integralLog.getIntegral() - integral);
                }
                integralLog.setIntegral(integral);
                saveOrUpdate(integralLog);
            }
        } else {
            integralLog = new DbIntegralLog();
            integralLog.setIntegral(integral);
            integralLog.setReadType(readType);
            integralLog.setUserId(userId);
            integralLog.setUserName(userName);
            integralLog.setNote("读书获得积分");
            integralLog.setType(1);
            integralLog.setSysNote(EmSysNotePlatform.tq_card.getType());
            integralLog.setDay(date);
            // Date now = new Date();
            // now = DateKit.dateFormat(DateKit.dateFormat(now,date+" HH:mm:ss"));
            // integralLog.setCreateTime(new Timestamp(now.getTime()));
            resultDto.setType(1);
            resultDto.setIntegral(integral);
        }
        saveOrUpdate(integralLog);
        return resultDto;
    }

    @Override
    public AddNoteResultDto queryCardByToday(List<DbUserNoteDto> dtos) {
        DbUserNoteDto dto = dtos.get(0);
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        Integer readType = 3;
        DbIntegralLog integralLog = null;
        // 查询连续打卡天数
        // 查询昨日打卡
        Integer integral = null;
        String note = "";
        String userId = dto.getUserId();
        DbCard yesterdayCard = dbCardService.queryYesterdayCardByUserId(dto.getUserId());

        DbCard todayCard = dbCardService.queryTodayCardByUserId(dto.getUserId());
        DbUser user = dbUserService.getById(userId);
        String userName = user.getUserName();
        Date now = new Date();
        String day = DateKit.dateFormat(now, "yyyy-MM-dd");
        if (UtilValidate.isEmpty(todayCard)) {
            if (UtilValidate.isNotEmpty(yesterdayCard)) {
                if (UtilValidate.isNotEmpty(user.getContinuousNum())) {
                    Integer continuousNum = user.getContinuousNum() + 1;// 跨月无法感知

                    // 查询提前打卡的连续天数
                    Integer userAdvanceDays = dbCardService.getRangeDateNowCard(day);

                    if (userAdvanceDays > 0) {
                        log.info("--" + userName + "提前读书::" + userAdvanceDays);
                        continuousNum += userAdvanceDays;
                    }
                    if (continuousNum.equals(10)) {
                        integral = 10;
                        note = "连续签到获得";
                    }
                    if (continuousNum == 20) {
                        integral = 20;
                        note = "连续签到获得";
                    }
                    if (continuousNum > 20) {

                        continuousNum = 1;

                        dbUserSignService.addStartUser(userId, userName, day, "日常打卡");

                    }
                    // if(UtilValidate.isNotEmpty(integral)){
                    // user.setIntegral(user.getIntegral()+integral);
                    // }

                    user.setContinuousNum(continuousNum);
                } else {
                    user.setContinuousNum(1);
                }
                dbUserService.saveOrUpdate(user);
            } else {
                user.setContinuousNum(1);
                dbUserSignService.addStartUser(userId, userName, day, "日常打卡");

                dbUserService.saveOrUpdate(user);
            }
        }

        if (UtilValidate.isNotEmpty(integral)) {
            DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
            criteria.setType(1);
            criteria.setReadType(readType);
            criteria.setUserId(dto.getUserId());
            criteria.setSysNote(EmSysNotePlatform.da_day.getType());
            criteria.setDay(day);
            // Date date = new Date();
            // String start = DateKit.dateFormat(date, "yyyy-MM-dd 00:00:00");
            // String end = DateKit.dateFormat(date, "yyyy-MM-dd 23:59:59");
            // List<String> list=new ArrayList<>();
            // list.add(start);
            // list.add(end);
            // List<String> list=DateUtils.getDateListByThisDay();
            // criteria.setCreateTime(list);
            // 查询今日的连续打卡积分
            List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);

            if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
                integralLog = dbIntegralLogs.get(0);
            } else {
                integralLog = new DbIntegralLog();
                // integral
                integralLog.setIntegral(integral);
                integralLog.setReadType(readType);
                integralLog.setUserId(dto.getUserId());
                integralLog.setUserName(dto.getUserName());
                integralLog.setNote(note);
                integralLog.setType(1);
                integralLog.setDay(day);
                integralLog.setSysNote(EmSysNotePlatform.da_day.getType());
                saveOrUpdate(integralLog);
                result.setType(1);
                result.setIntegral(integral);

            }
        }

        return result;
    }

    /**
     * 在假设 当前日期打卡记录已插入数据的情况下
     * 计算 连续打卡了几天，判断标准 1今天是否有这正常打卡，2 从今今天到传入的日期这段时间是不是连续的
     *
     * @param dtos
     * @param date
     * @return
     */
    @Override
    public AddNoteResultDto queryAdvanceCardByDate(List<DbUserNoteDto> dtos, String date) {
        DbUserNoteDto dto = dtos.get(0);
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        Integer readType = 3;
        DbIntegralLog integralLog = null;
        // 查询连续打卡天数
        // 查询昨日打卡
        Integer integral = null;
        String note = "";

        // getRangeDateCards

        // DbCard yesterdayCard =
        // dbCardService.queryAdvanceYesterdayByDate(dto.getUserId(),date);

        // DbCard todayCard =
        // dbCardService.queryDateCardByUserId(dto.getUserId(),date);//查询那天有没有打卡

        DbCard thisDayCard = dbCardService.queryTodayCardByUserId(dto.getUserId());// 查询今天有没有打卡

        Date now = new Date();

        String userId = getUserId();
        String userName = getUserName();
        DbUser user = dbUserService.getById(userId);
        DbUser n_user = new DbUser();
        n_user.setUserId(userId);

        String start = DateKit.dateFormat(now, "yyyy-MM-dd");

        // 跨月0点时会出现这情况
        if (UtilValidate.isEmpty(thisDayCard) && start.equals(date)) {

            DbUserAdvanceDateQueryCriteria c2 = new DbUserAdvanceDateQueryCriteria();
            c2.setUserId(userId);
            c2.setDay(date);
            List<DbUserAdvanceDate> endDates = dbUserAdvanceDateService.queryAll(c2);
            if (UtilValidate.isEmpty(endDates)) {
                // 插入结束日期
                DbUserAdvanceDate advanceDate = new DbUserAdvanceDate();
                advanceDate.setDay(date);
                advanceDate.setUserId(userId);
                advanceDate.setUserName(userName);
                dbUserAdvanceDateService.addOneFn(advanceDate);
            }
            if (UtilValidate.isNotEmpty(user.getContinuousNum())) {
                Integer continuousNum = user.getContinuousNum() + 1;
                if (continuousNum.equals(10)) {
                    integral = 10;
                    note = "连续签到获得";
                }
                if (continuousNum == 20) {
                    integral = 20;
                    note = "连续签到获得";
                }
                if (continuousNum > 20) {
                    continuousNum = 1;
                    dbUserSignService.addStartUser(userId, userName, date, "提前读书");

                }
                user.setContinuousNum(continuousNum);
            } else {
                user.setContinuousNum(1);
                dbUserSignService.addStartUser(userId, userName, date, "提前读书");

            }
            n_user.setContinuousNum(user.getContinuousNum());
            dbUserService.updateById(n_user);
        }

        // 今天已经打了卡 并且和提前读书 的那一天已经连接在了一起
        if (UtilValidate.isNotEmpty(thisDayCard)) {

            Integer rangeDateCards = dbCardService.getRangeDateCards(start, date);// 今天到提起读书的那一天都是连续的

            if (rangeDateCards > 0) {
                if (UtilValidate.isNotEmpty(user.getContinuousNum())) {
                    Integer continuousNum = user.getContinuousNum() + rangeDateCards;// 跨月无法感知
                    if (continuousNum == 20) {
                        integral = 20;
                        note = "连续签到获得";
                    }
                    if (continuousNum > 20) {
                        continuousNum = 1;
                        dbUserSignService.addStartUser(userId, userName, date, "提前读书");

                    }
                    user.setContinuousNum(continuousNum);
                } else {
                    dbUserSignService.addStartUser(userId, userName, date, "提前读书");
                    user.setContinuousNum(1);
                }
                n_user.setContinuousNum(user.getContinuousNum());
                dbUserService.updateById(n_user);
            } else {
                user.setContinuousNum(1);
                n_user.setContinuousNum(user.getContinuousNum());
                dbUserService.updateById(n_user);
            }
        }

        if (UtilValidate.isNotEmpty(integral)) {
            DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
            criteria.setType(1);
            criteria.setReadType(readType);
            criteria.setUserId(dto.getUserId());
            criteria.setIntegral(integral);
            criteria.setSysNote(EmSysNotePlatform.tq_card.getType());
            criteria.setDay(date);
            // List<String> list=DateUtils.getDateListByThisDay();
            // criteria.setCreateTime(list);
            // 查询今日的连续打卡积分
            List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);

            if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
                integralLog = dbIntegralLogs.get(0);
            } else {
                integralLog = new DbIntegralLog();
                // integral
                integralLog.setIntegral(integral);
                integralLog.setReadType(readType);
                integralLog.setUserId(dto.getUserId());
                integralLog.setUserName(dto.getUserName());
                integralLog.setNote(note);
                integralLog.setType(1);
                integralLog.setSysNote(EmSysNotePlatform.tq_card.getType());
                integralLog.setDay(date);
                saveOrUpdate(integralLog);
                result.setType(1);
                result.setIntegral(integral);

            }
        }

        return result;
    }

    @Override
    public AddNoteResultDto queryFullByToday(DbCard card) {

        // type 0 未达到 满勤或全勤的条件 1 新增 2 已经存在
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        DbIntegralLog integralLog = null;

        boolean isFull = false;

        if (UtilValidate.isNotEmpty(card.getIsFullMonth()) && card.getIsFullMonth() == 1 ||
                UtilValidate.isNotEmpty(card.getIsAllMonth()) && card.getIsAllMonth() == 1
//                ||
//                UtilValidate.isNotEmpty(card.getIsFullYear()) && card.getIsFullYear() == 1 ||
//                UtilValidate.isNotEmpty(card.getIsAllYear()) && card.getIsAllYear() == 1
        ) {
            isFull = true;
        }
        if (isFull) {
            Integer readType = 1;
            DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
            criteria.setType(1);
            criteria.setReadType(readType);
            criteria.setUserId(card.getUserId());
            Date date = new Date();
            String start = DateKit.dateFormat(date, "yyyy-MM-dd 00:00:00");
            String end = DateKit.dateFormat(date, "yyyy-MM-dd 23:59:59");
            List<String> list = new ArrayList<>();
            list.add(start);
            list.add(end);
            criteria.setCreateTime(list);
            // 查询满勤或全勤积分
            List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);
            if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
                integralLog = dbIntegralLogs.get(0);

                result.setType(2);
            } else {
                String note = "";
                Integer integral = 0;
                if (UtilValidate.isNotEmpty(card.getIsFullMonth()) && card.getIsFullMonth() == 1) {
                    integral = 10;
                    note = "月满勤";
                }
                if (UtilValidate.isNotEmpty(card.getIsAllMonth()) && card.getIsAllMonth() == 1) {
                    integral = 30;
                    note = "月全勤";
                }
//                if (card.getIsFullYear() == 1) {
//                    // integral=50;
//                    // note="年满勤";
//                }
//                if (card.getIsAllYear() == 1) {
//                    // integral=100;
//                    // note="年全勤";
//                }

                integralLog = new DbIntegralLog();
                integralLog.setIntegral(integral);
                integralLog.setReadType(readType);
                integralLog.setUserId(card.getUserId());
                integralLog.setUserName(card.getUserName());
                integralLog.setNote(note);
                integralLog.setType(1);
                saveOrUpdate(integralLog);
                result.setType(1);
                result.setIntegral(integral);
                result.setNote(note);

            }
        } else {

        }

        return result;
    }

    @Override
    public AddNoteResultDto queryFullByDate(DbCard card, String dateStr) {
        // type 0 未达到 满勤或全勤的条件 1 新增 2 已经存在
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        DbIntegralLog integralLog = null;

        boolean isFull = false;

        if (UtilValidate.isNotEmpty(card.getIsFullMonth()) && card.getIsFullMonth() == 1 ||
                UtilValidate.isNotEmpty(card.getIsAllMonth()) && card.getIsAllMonth() == 1
//                UtilValidate.isNotEmpty(card.getIsFullYear()) && card.getIsFullYear() == 1 ||
//                UtilValidate.isNotEmpty(card.getIsAllYear()) && card.getIsAllYear() == 1
        ) {
            isFull = true;
        }
        if (isFull) {
            Integer readType = 1;
            DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
            criteria.setType(1);
            criteria.setReadType(readType);
            criteria.setUserId(card.getUserId());
            // Date date = new Date();
            // String start = DateKit.dateFormat(date, "yyyy-MM-dd 00:00:00");
            // String end = DateKit.dateFormat(date, "yyyy-MM-dd 23:59:59");
            String start = dateStr + " 00:00:00";
            String end = dateStr + " 23:59:59";
            List<String> list = new ArrayList<>();
            list.add(start);
            list.add(end);
            criteria.setCreateTime(list);
            // 查询满勤或全勤积分
            List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);
            if (UtilValidate.isNotEmpty(dbIntegralLogs)) {
                integralLog = dbIntegralLogs.get(0);

                result.setType(2);
            } else {
                String note = "";
                Integer integral = 0;
                if (card.getIsFullMonth() == 1) {
                    integral = 10;
                    note = "月满勤";
                }
                if (card.getIsAllMonth() == 1) {
                    integral = 30;
                    note = "月全勤";
                }
//                if (card.getIsFullYear() == 1) {
//                    integral = 50;
//                    note = "年满勤";
//                }
//                if (card.getIsAllYear() == 1) {
//                    integral = 100;
//                    note = "年全勤";
//                }
                integralLog = new DbIntegralLog();
                integralLog.setIntegral(integral);
                integralLog.setReadType(readType);
                integralLog.setUserId(card.getUserId());
                integralLog.setUserName(card.getUserName());
                integralLog.setNote(note);
                integralLog.setSysNote("补卡");
                integralLog.setType(1);

                Date now = new Date();
                now = DateKit.dateFormat(DateKit.dateFormat(now, dateStr + " HH:mm:ss"));
                Timestamp countTime = new Timestamp(now.getTime());
                integralLog.setCreateTime(countTime);

                saveOrUpdate(integralLog);

                // 添加积分 补卡满勤积分加入
                DbUser user = dbUserService.getById(card.getUserId());
                Integer total = user.getIntegral() + integral;
                user.setIntegral(total);
                dbUserService.saveOrUpdate(user);

                result.setType(1);
                result.setIntegral(integral);
                result.setNote(note);

            }
        } else {

        }

        return result;
    }


    @Override
    public void queryFullByDateNoCard(String date, DbCard card) {

        Date now = new Date();
        now = DateKit.dateFormat(DateKit.dateFormat(now, date + " HH:mm:ss"));
        String day = date;
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");

        Integer readType = 1;
        DbIntegralLogQueryCriteria criteria = new DbIntegralLogQueryCriteria();
        criteria.setType(1);
        criteria.setReadType(readType);
        criteria.setUserId(card.getUserId());
        String start = date + " 00:00:00";
        String end = date + " 23:59:59";
        List<String> list = new ArrayList<>();
        list.add(start);
        list.add(end);
        criteria.setCreateTime(list);
        // 查询满勤或全勤积分
        List<DbIntegralLog> dbIntegralLogs = queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbIntegralLogs)) {


        } else {
            String note = "";
            Integer integral = 0;
            if (card.getIsFullMonth() == 1) {
                integral = 10;
                note = "月满勤";
            }
            if (card.getIsAllMonth() == 1) {
                integral = 30;
                note = "月全勤";
            }

            // 判断是否月 满勤 全勤
            // 统计 这个月的打卡天数 不连续
            Integer dayCount = dbCardService.countDaysContinuous(card.getUserId(), month);
            // 获取当前年月
            YearMonth yearMonth = YearMonth.now();
            // 获取这个月有多少天
            int countMonthDays = yearMonth.lengthOfMonth();
            // 统计 这年的打卡月数 不连续
            //    Integer monthCount = countMonthsContinuous(userId, year);
            // 月 满勤 24 天 并且 要没有满勤过

            DbCard fullMonth = dbCardService.queryFullMonth(card.getUserId(), month);
            card.setIsFullMonth(0);
            if (dayCount >= 24 && UtilValidate.isEmpty(fullMonth)) {
                card.setIsFullMonth(1);
                integral = 10;
                note = "月满勤";
            }
            // 月 全勤 所有天 天
            card.setIsAllMonth(0);
            if (dayCount >= countMonthDays) {
                card.setIsAllMonth(1);
                integral = 30;
                note = "月全勤";
            }
            dbCardService.saveOrUpdate(card);

            DbIntegralLog integralLog = new DbIntegralLog();
            integralLog.setIntegral(integral);
            integralLog.setReadType(readType);
            integralLog.setUserId(card.getUserId());
            integralLog.setUserName(card.getUserName());
            integralLog.setNote(note);
            integralLog.setSysNote("正常打卡");
            integralLog.setType(1);

            Timestamp countTime = new Timestamp(now.getTime());
            integralLog.setCreateTime(countTime);
            saveOrUpdate(integralLog);

            // 添加积分 补卡满勤积分加入
            DbUser user = dbUserService.getById(card.getUserId());
            Integer total = user.getIntegral() + integral;
            user.setIntegral(total);
            dbUserService.saveOrUpdate(user);

            //发送消息
            if(!"dev".equals(PD_MATCH)){
                dingMiniNoticeService.sendReadIntegralMsg(integralLog);
            }else{
                System.out.println("--本地模拟发送消息"+integralLog);
            }
        }
    }



    /**
     * 打卡
     * 累计5分钟判断
     *
     * @param list
     * @return
     */
    @Override
    public AddNoteResultDto addReadTypeByToday(List<DbUserNoteDto> list) {
        DbUserNoteDto dto = list.get(0);
        String userId = getUserId();
        DbUserNoteQueryCriteria noteQueryCriteria = new DbUserNoteQueryCriteria();
        noteQueryCriteria.setUserId(userId);
        // String day = DateUtils.getDateStrByBefore8_30();
        Date now = new Date();
        String day = DateKit.dateFormat(now, "yyyy-MM-dd");
        noteQueryCriteria.setDay(day);
        noteQueryCriteria.setSysNoteIsNull("1");
        BigDecimal userDurations = dbUserNoteService.getUserDurations(noteQueryCriteria);
        BigDecimal allTime = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            DbUserNoteDto noteDto = list.get(i);
            allTime = allTime.add(noteDto.getDuration());
        }
        if (UtilValidate.isNotEmpty(userDurations)) {
            allTime = allTime.add(userDurations);
        }
        // 5分钟 原本是300 ，但实际可能会差个0.0秒

        String remoteUrl = dto.getRemoteUrl();
        BigDecimal fiveMinute = null;// 5分钟
        BigDecimal startMinute = null;// 起点分钟数 2.5分钟=150秒
        if (remoteUrl.contains(".ogg")) {
            startMinute = new BigDecimal("150");
            fiveMinute = new BigDecimal("299");
        } else {
            startMinute = new BigDecimal("150000");
            fiveMinute = new BigDecimal("299000");
        }
        Integer integral = 0;
        // 大于2.5小于5分钟
        if (allTime.compareTo(startMinute) >= 0 && allTime.compareTo(fiveMinute) < 0) {
            integral = 1;
        } else if (allTime.compareTo(fiveMinute) >= 0) {
            // 大于5分钟
            integral = 2;
        }
        // int r = allTime.compareTo(fiveMinute);
        // if(r>=0){
        // integral=2;
        // }
        // 是否打过卡
        boolean isCards = false;
        // 查询打卡记录
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(day);
        criteria.setUserId(userId);

        List<DbCard> dbCards = dbCardService.queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            isCards = true;
        }

        // type 0 未达到 满勤或全勤的条件 1 新增 2 已经存在
        // 今日读书获得积分
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        if (integral > 0) {
            result = queryReadTypeByToday(dto, integral);
        }
        BigDecimal twoMinute = null;
        if (remoteUrl.contains(".ogg")) { // 2.5分钟
            twoMinute = new BigDecimal("150");
        } else {
            twoMinute = new BigDecimal("150000");
        }

        // 还没打过卡可进行 还差多少分钟才能打卡成功的提示
        if (result.getType().equals(0) && !isCards) {
            BigDecimal b_residueTimes = twoMinute.subtract(allTime).divide(new BigDecimal(60), 2,
                    BigDecimal.ROUND_HALF_UP);
            result.setResidueTimes(b_residueTimes.doubleValue() + "");
        }
        return result;

    }

    public AddNoteResultDto patchReadTypeByToday(List<DbUserNoteDto> list, String date) {

        DbUserNoteDto dto = list.get(0);
        DbUserNoteQueryCriteria noteQueryCriteria = new DbUserNoteQueryCriteria();
        noteQueryCriteria.setUserId(dto.getUserId());

        noteQueryCriteria.setDay(date);
        BigDecimal userDurations = dbUserNoteService.getUserDurations(noteQueryCriteria);

        // 是否打过卡
        boolean isCards = false;
        // 查询打卡记录
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(date);
        criteria.setUserId(dto.getUserId());

        List<DbCard> dbCards = dbCardService.queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            isCards = true;
        }

        BigDecimal allTime = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            DbUserNoteDto noteDto = list.get(i);
            allTime = allTime.add(noteDto.getDuration());
        }
        if (UtilValidate.isNotEmpty(userDurations)) {
            allTime = allTime.add(userDurations);
        }
        // 15分钟 900秒

        String remoteUrl = dto.getRemoteUrl();
        BigDecimal fiveMinute = null;
        if (remoteUrl.contains(".ogg")) {
            fiveMinute = new BigDecimal("900");
        } else {
            fiveMinute = new BigDecimal("900000");
        }

        int r = allTime.compareTo(fiveMinute);
        Integer integral = 0;
        if (r >= 0) {
            integral = 1;
        }
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        // 添加积分记录
        if (integral > 0) {
            // 当日读书获得积分
            result = patchReadTypeByToday(dto, integral, date);
            // 更新打卡连续签到次数
            // DbUser u=new DbUser();
            // u.setUserId(dto.getUserId());
            // u.setContinuousNum(1);
            // dbUserService.updateById(u);
        }
        // 还没打过卡可进行 还差多少分钟才能打卡成功的提示
        if (result.getType().equals(0) && !isCards) {
            BigDecimal b_residueTimes = fiveMinute.subtract(allTime).divide(new BigDecimal(60), 2,
                    BigDecimal.ROUND_HALF_UP);
            result.setResidueTimes(b_residueTimes.doubleValue() + "");
        }
        return result;
    }

    @Override
    public AddNoteResultDto advanceReadTypeByToday(List<DbUserNoteDto> list, String date) {
        DbUserNoteDto dto = list.get(0);
        DbUserNoteQueryCriteria noteQueryCriteria = new DbUserNoteQueryCriteria();
        String userId = getUserId();
        noteQueryCriteria.setUserId(userId);
        noteQueryCriteria.setSysNote(EmSysNotePlatform.tq_card.getType());
        noteQueryCriteria.setDay(date);
        BigDecimal userDurations = dbUserNoteService.getUserDurations(noteQueryCriteria);

        // 是否打过卡
        boolean isCards = false;
        // 查询打卡记录
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(date);
        criteria.setUserId(userId);

        List<DbCard> dbCards = dbCardService.queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            isCards = true;
        }

        BigDecimal allTime = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            DbUserNoteDto noteDto = list.get(i);
            allTime = allTime.add(noteDto.getDuration());
        }
        if (UtilValidate.isNotEmpty(userDurations)) {
            allTime = allTime.add(userDurations);
        }
        // 15分钟 900秒

        String remoteUrl = dto.getRemoteUrl();
        BigDecimal endMinute = null;// 终点 15分钟 =900秒
        BigDecimal startMinute = null;// 起点分钟数 10分钟=600秒
        if (remoteUrl.contains(".ogg")) {
            startMinute = new BigDecimal("600");
            endMinute = new BigDecimal("900");
        } else {
            startMinute = new BigDecimal("600000");
            endMinute = new BigDecimal("900000");
        }
        Integer integral = 0;
        // 大于10分钟小于15分钟
        if (allTime.compareTo(startMinute) >= 0 && allTime.compareTo(endMinute) < 0) {
            integral = 1;
        } else if (allTime.compareTo(endMinute) >= 0) {
            // 大于15分钟
            integral = 2;
        }

        // type 0 未达到 满勤或全勤的条件 1 新增 2 已经存在
        // 今日读书获得积分
        AddNoteResultDto result = new AddNoteResultDto();
        result.setType(0);
        if (integral > 0) {
            result = advanceReadTypeByToday(dto, integral, date);
        }
        // 还没打过卡可进行 还差多少分钟才能打卡成功的提示
        if (result.getType().equals(0) && !isCards) {
            BigDecimal b_residueTimes = startMinute.subtract(allTime).divide(new BigDecimal(60), 2,
                    BigDecimal.ROUND_HALF_UP);
            result.setResidueTimes(b_residueTimes.doubleValue() + "");
        }
        if (isCards) {
            // 二阶段提示
            if (allTime.compareTo(endMinute) < 0) {
                // 剩余时长
                BigDecimal subtract = endMinute.subtract(allTime).divide(new BigDecimal(60), 2,
                        BigDecimal.ROUND_HALF_UP);

                result.setNextMsg("打卡成功,下一阶段目标15分钟您还差" + subtract.doubleValue() + "分钟即可再领取1积分！");
            }
        } else {
            if (result.getType().equals(1) && allTime.compareTo(endMinute) < 0) {
                // 一阶段提示
                BigDecimal subtract = endMinute.subtract(allTime).divide(new BigDecimal(60), 2,
                        BigDecimal.ROUND_HALF_UP);
                result.setNextMsg("打卡成功,下一阶段目标15分钟您还差" + subtract.doubleValue() + "分钟即可再领取1积分！");
            }
        }
        return result;
    }

    @Override
    public TableList<SysRankingListDto> sysRankingList(SysRankingQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        List<SysRankingListDto> maps = baseMapper.sysRankingList(criteria);
        PageInfo<SysRankingListDto> pageInfo = new PageInfo<>(maps);
        TableList<SysRankingListDto> tableList = new TableList<>(pageInfo);
        return tableList;
    }

    @Override
    public SysRankingListDto getUserReadIntegral(SysRankingQueryCriteria criteria) {
        SysRankingListDto result = null;
        List<SysRankingListDto> maps = baseMapper.sysRankingList(criteria);
        if (UtilValidate.isNotEmpty(maps)) {
            result = maps.get(0);
        }
        return result;
    }

    @Override
    public TableList<SysRankingListDto> rankingIntegralList(SysRankingQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        List<SysRankingListDto> maps = baseMapper.rankingIntegralList(criteria);
        PageInfo<SysRankingListDto> pageInfo = new PageInfo<>(maps);
        TableList<SysRankingListDto> tableList = new TableList<>(pageInfo);
        return tableList;
    }

    @Override
    public Integer countUserIntegral(DbIntegralLogQueryCriteria criteria) {
        return baseMapper.countUserIntegral(criteria);
    }

    @Override
    public void continuousNumCompensation() {
        List<DbUser> users = baseMapper.getContinuousNumCompensation();
        Integer readType = 3;
        Date date = new Date();
        String day = DateKit.dateFormat(date, "yyyy-MM-dd");
        for (DbUser u : users) {
            DbIntegralLog integralLog = new DbIntegralLog();
            integralLog.setIntegral(10);
            integralLog.setReadType(readType);
            integralLog.setUserId(u.getUserId());
            integralLog.setUserName(u.getUserName());
            integralLog.setNote("连续签到获得");
            integralLog.setType(1);
            saveOrUpdate(integralLog);

            DbCardQueryCriteria criteria = new DbCardQueryCriteria();
            criteria.setUserId(u.getUserId());
            criteria.setDay(day);
            DbUser u2 = new DbUser();
            u2.setUserId(u.getUserId());
            u2.setIntegral(u.getIntegral() + 10);
            Integer continuousNum = u.getContinuousNum();
            List<DbCard> dbCards = dbCardService.queryAll(criteria);
            if (UtilValidate.isNotEmpty(dbCards)) {
                continuousNum = 11;
            } else {
                continuousNum = 10;
            }
            u2.setContinuousNum(continuousNum);
            dbUserService.updateById(u2);

        }
    }

    @Override
    public void sysUserDeduct(DbIntegralLog dbIntegralLog) {
        if (UtilValidate.isEmpty(dbIntegralLog.getNote())) {
            throw new YmException("请输入扣除理由!");
        }
        if (UtilValidate.isEmpty(dbIntegralLog.getIntegral())) {
            throw new YmException("请输入积分!");

        }
        String userId = dbIntegralLog.getUserId();
        DbUser user = dbUserService.getById(userId);
        if (dbIntegralLog.getIntegral() > user.getIntegral()) {
            throw new YmException("用户积分不足无法扣除!");
        }
        dbIntegralLog.setNote(dbIntegralLog.getNote() + "扣除积分");
        dbIntegralLog.setType(2);
        dbIntegralLog.setSysRemark("管理员扣除");
        saveOrUpdate(dbIntegralLog);
        DbUser n_u = new DbUser();
        n_u.setUserId(userId);
        n_u.setIntegral(user.getIntegral() - dbIntegralLog.getIntegral());
        dbUserService.updateById(n_u);
    }

    @Override
    public void sysUserAddReadIntegral(DbIntegralLog dbIntegralLog) {
        if (UtilValidate.isEmpty(dbIntegralLog.getNote())) {
            throw new YmException("请输入增加理由!");
        }
        if (UtilValidate.isEmpty(dbIntegralLog.getIntegral())) {
            throw new YmException("请输入积分!");

        }
        String userId = dbIntegralLog.getUserId();
        DbUser user = dbUserService.getById(userId);

        dbIntegralLog.setNote(dbIntegralLog.getNote() + "增加读书积分");
        dbIntegralLog.setType(1);
        dbIntegralLog.setReadType(2);
        dbIntegralLog.setSysRemark("管理员增加");

        if (UtilValidate.isEmpty(dbIntegralLog.getDay())) {
            Date date = new Date();
            String day = DateKit.dateFormat(date, "yyyy-MM-dd");
            dbIntegralLog.setDay(day);
        }
        saveOrUpdate(dbIntegralLog);
        DbUser n_u = new DbUser();
        n_u.setUserId(userId);
        n_u.setIntegral(user.getIntegral() + dbIntegralLog.getIntegral());
        dbUserService.updateById(n_u);
    }

    @Override
    public Integer sumIntegralTotal(SysRankingQueryCriteria criteria) {
        return baseMapper.sumIntegralTotal(criteria);
    }

    @Override
    public Double allTotalResidue(SysRankingQueryCriteria criteria) {
        return baseMapper.allTotalResidue(criteria);
    }
}
